import { useEffect, useState } from 'react';
import { useSelector, useDispatch } from "react-redux";
import { IStore } from '../redux/typings';
import { getType, updateIssueTypeId, updateBookTypeId } from '../redux/typeList';
import { Tag } from "antd"
import { useLocation } from 'react-router-dom';

const TypeSelect = () => {
    const { typeList } = useSelector((state: IStore) => state.type)
    const dispatch = useDispatch();
    const location = useLocation();
    const colorArr = ["#108ee9", "#2db7f5", "#f50", "green", "#87d068", "blue", "red", "purple"];
    const [tagContainer, setTagContainer] = useState<JSX.Element[]>([])

    useEffect(() => {
        if (!typeList.length) {
            dispatch((getType as any)());
        }
        if (typeList.length) {
            // 已经存储分类信息
            const arr = [];
            arr.push(<Tag
                color="magenta"
                key="all"
                style={{ cursor: "pointer" }}
                onClick={() => { changeType("all") }}
            >全部</Tag>)
            for (let i = 0; i < typeList.length; i++) {
                arr.push(<Tag
                    color={colorArr[i % colorArr.length]}
                    key={typeList[i]._id}
                    style={{ cursor: "pointer" }}
                    onClick={() => { changeType(typeList[i]._id) }}
                >{typeList[i].typeName}</Tag>)
            }
            setTagContainer(arr)
        }
    }, [typeList])

    const changeType = (value: string) => {
        // 更新状态仓库对应的issueTypeId
        if (location.pathname === '/issues') {
            // 处于问答页面
            dispatch(updateIssueTypeId(value))
        } else if (location.pathname === "/books") {
            // 书籍页面
            dispatch(updateBookTypeId(value))
        }
    }

    return (
        <div>
            {tagContainer}
        </div>
    );
}

export default TypeSelect;